// 封装购物车模块

import { defineStore } from "pinia";
import {ref} from 'vue'
import { computed } from 'vue';
import {useUserStore} from './user'
import {insertCartAPI,findNewCartListAPI,delCartAPI} from '@/apis/cart'

export const useCartStore = defineStore('cart',()=>{
    const userStore = useUserStore()
    const isLogin = computed(()=>userStore.userInfo.token)

    // 获取最新购物车列表
    async function updateNewList(){
      const res = await findNewCartListAPI()
      cartList.value = res.result
   }


    const cartList = ref([])
    // 添加购物车
    async function addCart(goods){
      const {skuId, count} = goods
      if(isLogin){
        // 登录之后的加入购物车逻辑
       await insertCartAPI({skuId,count})
       const res = await findNewCartListAPI()
       cartList.value = res.result
       
      }else{
       const item =  cartList.value.find(item =>goods.skuId === item.skuId)
        if(item){        
          item.count++
        }else{
          cartList.value.push(goods)
        }

      }
    }

    // 删除购物车
    async function delCart(skuId){
      if(isLogin){
       await delCartAPI([skuId])
       const res = await findNewCartListAPI()
       cartList.value = res.result
      }else{
        const index =  cartList.value.findIndex(item=> skuId === item.skuId)
        cartList.value.splice(index,1)

      }

    }

    // 清除购物车
    function clearCart(){
      cartList.value = []
    }
    // 计算属性
    // 1.总的数量 所有count之和
    // 2.总价 所有count * price之和
    // a是累加的那个变量  c是每一项
   const allCount = computed(()=> cartList.value.reduce((a,c)=>a + c.count,0))
   const allPrice = computed(()=> cartList.value.reduce((a,c)=>a + c.count * c.price,0))

   const selectedCount = computed(()=> cartList.value.filter(item=>item.selected).reduce((a,c)=>a + c.count,0))
   const selectedPrice = computed(()=> cartList.value.filter(item=>item.selected).reduce((a,c)=>a + c.count * c.price,0))


   // 全选功能
   function allCheck(selected){
    cartList.value.forEach(item=>item.selected = selected)

   }
   // 是否全选
   const isAll = computed(() => cartList.value.every((item) => item.selected))
   
    return {
        cartList,
        addCart,
        delCart,
        allCount,
        allPrice,
        isAll,
        allCheck,
        selectedCount,
        selectedPrice,
        clearCart,
        updateNewList
    }

},{
    persist:true
})